import json
import time

from flask import Flask, render_template
from flask_socketio import SocketIO
from flask_socketio import Namespace
import eventlet


class MyCustomNamespace(Namespace):

    def on_connect(self):
        print("Client just connected")
        return

    def on_disconnect(self):
        print('disconnect')

    def send_to_front(self, data):
        print('****************** i am send_to_front******************')
        # {'linear': {'x': 0.0, 'y': 0.0, 'z': 0.0}, 'angular': {'x': 1.0, 'y': 2.0, 'z': 3.0}}
        print(data)
        # <class 'dict'>
        print(type(data))
        # web端展示:Echarts_Xaxis要展示time:新增time
        t = time.strftime('%M:%S', time.localtime())
        print(t)
        # dict新增key和Value
        data['time'] = t
        self.socketio.emit('front',
                           data,
                           namespace='/channel_A', broadcast=True)
        # print(json.dumps(data))
        # print(type(json.dumps(data)))
        # self.socketio.emit('front',
        #                    json.dumps(data),
        #                    namespace='/channel_A', broadcast=True)

    def send_to_rosbridge(self, *data):
        print('****************change dataType:tuple->list pythonClient 2.receive operation message from FlaskServer')
        # <class 'tuple'>
        print(data)
        # <class 'list'>
        # print(data[0])
        self.socketio.emit('diegoserver',
                           data[0],
                           namespace='/channel_A', broadcast=True)

    def on_rosbridge(self, data):  # response for rosbridge
        print('********** i am on_rosbridge****************')
        print(data)
        # print(type(data))
        self.send_to_front(data)

    def on_operation(self, *data):  # response for web client
        print('****************check out 1.receive operation message from web roblibjs client')
        # 负责检测：webTobridge01.html发出的数据结构
        print(data)
        # print(data[0])
        # print(data[0][0])
        # print(data[0][1])
        print('**************** type in operation***************')
        # print(type(data))
        # print(type(data[0]))
        # print(type(data[0][0]))
        # print(type(data[0][1]))
        self.send_to_rosbridge(*data)

    def on_operationListener(self, *data):  # response for web client
        print('****************check out 1.receive operationListener message from web roblibjs client')
        # 负责检测：webTobridge01.html发出的数据结构
        print(data)
        # print(data[0])
        # print(data[0][0])
        print('**************** type in operationListener***************')
        # print(type(data))
        # print(type(data[0]))
        # print(type(data[0][0]))
        self.send_to_rosbridge(*data)
